<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

require_once 'db.php';

try {
    // 获取参数
    $user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
    $type = isset($_GET['type']) ? intval($_GET['type']) : 0;

    if (!$user_id || !$type) {
        throw new Exception('参数错误');
    }

    // 查询预约记录
    $sql = "SELECT b.*, 
            CASE 
                WHEN b.type = 1 THEN c1.name 
                ELSE c2.name 
            END as coach_name,
            CASE 
                WHEN b.type = 1 THEN c1.avatar 
                ELSE c2.avatar 
            END as coach_avatar,
            cs.name as course_name,
            cs.cover_image as course_image,
            cs.category_id,
            cc.name as category_name,
            CASE 
                WHEN b.type = 1 THEN c1.description
                ELSE cs.description
            END as description
            FROM bookings b
            LEFT JOIN coaches c1 ON b.coach_id = c1.id
            LEFT JOIN courses cs ON b.course_id = cs.id
            LEFT JOIN coaches c2 ON cs.coach_id = c2.id
            LEFT JOIN course_categories cc ON cs.category_id = cc.id
            WHERE b.user_id = ? AND b.type = ?
            ORDER BY b.created_at DESC";

    $stmt = $conn->prepare($sql);
    if ($stmt === false) {
        throw new Exception('SQL预处理失败: ' . $conn->error);
    }

    $stmt->bind_param("ii", $user_id, $type);
    
    if (!$stmt->execute()) {
        throw new Exception('查询失败: ' . $stmt->error);
    }

    $result = $stmt->get_result();
    $bookings = [];
    
    while ($row = $result->fetch_assoc()) {
        // 格式化时间
        $row['created_at'] = date('Y-m-d H:i', strtotime($row['created_at']));
        $bookings[] = $row;
    }

    echo json_encode([
        'status' => 'success',
        'bookings' => $bookings
    ]);

} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
} finally {
    if (isset($stmt)) $stmt->close();
    if (isset($conn)) $conn->close();
}
?> 